<?php
namespace App\Services;
require_once $_SERVER["DOCUMENT_ROOT"]."/../app/Librarys/WxPay/lib/WxPay.Api.php";
require_once $_SERVER["DOCUMENT_ROOT"]."/../app/Librarys/WxPay/lib/WxPay.JsApiPay.php";
require_once $_SERVER["DOCUMENT_ROOT"]."/../app/Librarys/WxPay/lib/WxPay.Config.php";
// require_once $_SERVER["DOCUMENT_ROOT"]."/../app/Librarys/WxPay/lib/log.php";
// namespace App\Librarys\wilddog\src;
// use App\Librarys\WxPay\lib\JsApiPay;

class WxpayService
{
    public static function getOpenid()
    {
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        return $openId;
    }

    public static function getOrders($title,$price,$out_trade_no,$uid,$openid)
    {
        try{
            $tools = new \JsApiPay();
            $input = new \WxPayUnifiedOrder();
            // 订单标题
            $input->SetBody($title);
            // 订单附加信息(可选参数)
            $input->SetAttach($uid);
            // 订单号
            $input->SetOut_trade_no($out_trade_no);
            // 订单金额
            $input->SetTotal_fee($price*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag($title);
            $input->SetNotify_url("https://".$_SERVER['SERVER_NAME']."/api/wechat_notify");
            $input->SetTrade_type("JSAPI");
            // OPENID (必选参数)
            $input->SetOpenid($openid);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            $jsApiParameters = $tools->GetJsApiParameters($order);

            //获取共享收货地址js函数参数
            // $editAddress = $tools->GetEditAddressParameters();
            return ["status"=>"success","jsapi"=>json_decode($jsApiParameters)];
        } catch(\Exception $e) {
            return ["status"=>"error","jsapi"=>[]];
        }
    }

    public static function toXml($data): string
    {
        if (!is_array($data) || count($data) <= 0) {
            throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!', 2);
        }

        $xml = '<xml>';
        foreach ($data as $key => $val) {
            $xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
                                       '<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
        }
        $xml .= '</xml>';

        return $xml;
    }

    public static function fromXml($xml): array
    {
        if (!$xml) {
            throw new InvalidArgumentException('Convert To Array Error! Invalid Xml!', 3);
        }

        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
    }

}
